from operator import index
from tokenize import group

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import subplot, title, table, xticks, yticks

plt.rcParams['axes.unicode_minus']=False
plt.rcParams['font.sans-serif']=['SimHei']

#读取数据
years=range(1880,2023)
pipes=[]
for year in years:
    path=f'names/yob{year}.txt'
    frame=pd.read_csv(path,names=['name','sex','births'])
    frame['year']=year
    pipes.append(frame)

names=pd.concat(pipes,ignore_index=True)
#print(names.head())
def add_prop(group):
    group['prop']=group.births / group.births.sum()
    return group

names=names.groupby(['year','sex']).apply(add_prop)
names.reset_index(inplace=True,drop=True)
print(names.head())

def get_top1000(group):
    return group.sort_values(by='births',ascending=False)[:1000]
grouped=names.groupby(['year','sex'])
top1000=grouped.apply(get_top1000)
top1000.reset_index(inplace=True,drop=True)

total_births=names.pivot_table('births',index='year',columns='name',aggfunc=sum)
subset=total_births[['John','Harry','Mary','Marilyn']]
subset.plot(subplots=True,grid=False,title='命名趋势')
plt.show()

table=top1000.pivot_table('prop',index='year',columns='sex',aggfunc=sum)
table.plot(xticks=range(1880,2020,10),yticks=np.linspace(0,1.2,13),
           title='每年各性别前1000姓名比例')
plt.show()